$(document).ready(function() {

	var GlobalBean = {
		displayChartCount : 0,
		displayChartPointCount : 0,
		page : new Page(),
		selectedChart : {},
		filterCondition : {}
	};

	var DocBean = {
		buttons : {
			queryBtn : {
				ID : $("#f1_btn"),
				clickFnc : function() {
					DocBean.dialogs.queryDialog.showFnc();
				}
			},
			calcCPKBtn : {
				ID : $("#f5_btn"),
				calcCpkFnc : function() {
					var calChart, i;
					
					if (GlobalBean.page.chartCount <= 0) {
						showErrorDialog("", "请选择需要管制图后再计算");
						return false;
					}

					for (i = 0; i < GlobalBean.page.chartCount; i++) {
						if (GlobalBean.page.chartList[i].chart_typ == _CHART_TYPE_MEAN
								|| GlobalBean.page.chartList[i].chart_typ == _CHART_TYPE_SINGLE) {
							calChart = GlobalBean.page.chartList[i];
							break;
						}
					}
					calChart.caclCPk();
					DocBean.dialogs.calCpkDialog.showDialogFnc(calChart);
				}
			},
			clearBtn : {
				ID : $("#f10_btn"),
				clickFnc : function() {
					var chart = new Chart();
					// var currentWidth = GlobalBean.displayChartPointCount *
					// chart.initializeCanvas("chart", 1222, 550);
					var canvas = $("#chart");
					canvas.get(0).getContext("2d").clearRect(0, 0,
							canvas.width(), canvas.height());
					GlobalBean.displayChartCount = 0;
					GlobalBean.page = new Page();
					$("input:not(.noreset)").val("");
				}
			},
			filterBtn : {
				ID : $("#f2_btn"),
				clickFnc : function() {

				}
			},
			refreshBtn : {
				ID : $("#f3_refresh_btn"),
				clickFnc : function() {
					DocBean.buttons.clearBtn.clickFnc();
					showChart({
								col_typ_fk : GlobalBean.selectedChart.col_typ,
								grp_no_fk : GlobalBean.selectedChart.grp_no,
								chart_no : GlobalBean.selectedChart.chart_no
							}, true,true);

				}
			}
		},
		dialogs : {
			queryDialog : {
				ID : $("#queryDialog"),
				initFnc : function() {
					var queryDialog;
					var inObj,outObj,iary={};
					queryDialog = DocBean.dialogs.queryDialog;

					queryDialog.ID.modal({
								backdrop : true,
								keyboard : false,
								show : false
							});

					$("input").val("");
					$("select").empty();

					// queryDialog.ID.unbind('shown');
					queryDialog.buttons.queryBtn.unbind('click');
					queryDialog.elements.grpNameSel.ID.unbind("change");

					// queryDialog.ID.bind('shown', queryDialog.showFnc);
					queryDialog.buttons.queryBtn.bind('click',
							queryDialog.buttons.queryBtnClickFnc);
					queryDialog.elements.grpNameSel.ID.bind("change",
							queryDialog.elements.grpNameSel.onChangeFnc);

//					url = "listAllGroupMain";
//					outTrx = comSendAjax(_GET, url).outPo;
					iary={
						grp_no:null
					}
					inObj={
						trx_id: "FQPGRPMN",
						action_flg:"Q",
						iary:[iary]
					}
					outObj = comTrxSubSendPostJson(inObj);
					if (outObj.rtn_code == _NORMAL) {

						for (i = 0; i < outObj.oary.length; i++) {
                            SelectDom.addSelect($("#queryDialog_grpNameSel"),outObj.oary[i].grp_no,outObj.oary[i].grp_name);
							/*queryDialog.elements.grpNameSel.ID
									.append("<option value="
											+ outObj.oary[i].grp_no + ">"
											+ outObj.oary[i].grp_name
											+ "</option>");*/
						}
						// queryDialog.elements.grpNameSel.ID.val("000003");
						queryDialog.elements.grpNameSel.onChangeFnc();

					}

				},
				showFnc : function() {
					var queryDialog, url, outTrx;

					queryDialog = DocBean.dialogs.queryDialog;

					queryDialog.ID.modal("show");

					queryDialog.initFnc();

				},
				elements : {
					grpNameSel : {
						ID : $("#queryDialog_grpNameSel"),
						onChangeFnc : function() {
							var grp_no, url, inTrx, ouTrx,iary={};
							grp_no = DocBean.dialogs.queryDialog.elements.grpNameSel.ID
							.val();
//							url = "querySPCChartMainByCrit";
							iary={
								col_typ_fk : "2",
								grp_no_fk : grp_no=="undefined"?null:grp_no
							}
							inTrx = {
								trx_id  :"FQPCHTMN",
								action_flg:"Q",
								iary:[iary]
							};
//							var ouTrx = comSendAjax(_POST, url, inTrx).outPo;
							var ouTrx = comTrxSubSendPostJson(inTrx);
							if (ouTrx.rtn_code == _NORMAL) {
								setGridInfo(ouTrx.oary, '#chartListGrd');
							}
						}
					}

				},
				buttons : {
					queryBtn : $("#queryDialog_queryBtn"),
					queryBtnClickFnc : function() {
						var selRow, rowData;

						selRow = $("#chartListGrd").jqGrid("getGridParam",
								"selrow");
						rowData = $('#chartListGrd').jqGrid("getRowData",
								selRow);
						DocBean.buttons.clearBtn.clickFnc();
						showChart(rowData, true,true);
						$('#queryDialog').modal("hide");
					}
				}
			},
			calCpkDialog : {
				ID : $("#calCpkDialog"),
				elements : {
					meanTxt : $("#meanTxt"),
					stdDevTxt : $("#stdDevTxt"),
					sigmaTxt : $("#sigmaTxt"),
					caTxt : $("#caTxt"),
					cpTxt : $("#cpTxt"),
					cpkTxt : $("#cpkTxt"),
					ppTxt : $("#ppTxt"),
					ppkTxt : $("#ppkTxt"),
					gradeTxt : $("#gradeTxt")
				},
				initDialogFnc : function(calChart) {
					var dialogElems = DocBean.dialogs.calCpkDialog.elements;

					$("#calCpkDialogForm input").val("");

					dialogElems.meanTxt.val(calChart.mean);
					dialogElems.sigmaTxt.val(calChart.sigma);
					dialogElems.caTxt.val(calChart.ca);
					dialogElems.cpTxt.val(calChart.cp);
					dialogElems.cpkTxt.val(calChart.cpk);
					dialogElems.ppTxt.val(calChart.pp);
					dialogElems.ppkTxt.val(calChart.ppk);
					dialogElems.gradeTxt.val(calChart.grade);
				},
				showDialogFnc : function(calChart) {
					var calCpkDialog = DocBean.dialogs.calCpkDialog;
					calCpkDialog.ID.modal({
								backdrop : true,
								keyboard : false,
								show : false
							});
					calCpkDialog.ID.unbind('shown');
					calCpkDialog.ID.bind('shown', function() {
								calCpkDialog.initDialogFnc(calChart);
							}());
					calCpkDialog.ID.modal("show");
				},
				buttons : {

				}

			},
			filterChartDialog : {
				ID : $("#filterChartDialog"),
				elements : {
					mdlIDTxt : $("#filterChart_mdlIDSel"),
					eqptIDSel : $("#filterChart_eqptIDSel"),
					fromTimeIDTxt : $("#filterChart_fromTimeIDTxt"),
					toTimeIDTxt : $("#filterChart_toTimeIDTxt")
				},
				initDialogFnc : function(calChart) {
					var dialogElems = DocBean.dialogs.filterChartDialog.elements;

					dialogElems.eqptIDSel
					dialogElems.sigmaTxt.val(calChart.sigma);
					dialogElems.caTxt.vt.val(calChart.grade);
				},
				showDialogFnc : function(calChart) {
					var filterChartDialog = DocBean.dialogs.filterChartDialog;
					filterChartDialog.ID.modal({
								backdrop : true,
								keyboard : false,
								show : false
							});
					filterChartDialog.ID.unbind('shown');
					filterChartDialog.ID.bind('shown', function() {
								filterChartDialog.initDialogFnc(calChart);
							});
					filterChartDialog.ID.modal("show");
				},
				buttons : {

				}
			}
		},
		grids : {
			chartGrid : {
				initFnc : function() {
					var grdInfoCM = [{
								name : 'col_typ_fk',
								index : 'col_typ_fk',
								label : '数据类型',
								width : 50,
								hidden : true
							}, {
								name : 'grp_no_fk',
								index : 'grp_no_fk',
								label : '管制组代码',
								width : 120,
								hidden : true

							}, {
								name : 'chart_no',
								index : 'chart_no',
								label : '管制图编号',
								width : 200
							}, {
								name : 'data_group_fk',
								index : 'data_group_fk',
								label : '量测名称',
								size : 120
							}, {
								name : 'chart_typ',
								index : 'chart_typ',
								label : '管制图类型',
								size : 200
							}, {
								name : 'chart_sub_typ',
								index : 'chart_sub_typ',
								size : 200,
								hidden : true
							}, {
								name : 'chart_name',
								index : 'chart_name',
								label : '管制图名称',
								size : '120px'
							}, {
								name : 'chart_dsc',
								index : 'chart_dsc',
								label : '管制图描述',
								size : '150px'
							}, {
								name : 'chart_owner',
								index : 'chart_owner',
								label : '管制图负责人',
								size : '100px'
							}, {
								name : 'sample_size',
								index : 'sample_size',
								label : '样本数',
								size : '200px',
								hidden : true
							}, {
								name : 'max_chart_point',
								index : 'max_chart_point',
								label : '最大接收点数',
								size : '80px'
							}, {
								name : 'raw_keep_flg',
								index : 'raw_keep_flg',
								label : '保留原数据',
								size : '200px',
								hidden : true
							}, {
								name : 'evt_usr',
								index : 'evt_usr',
								label : '事件用户',
								size : '120px',
								sortable : true
							}, {
								name : 'evt_timestamp',
								index : 'evt_timestamp',
								label : '事件时间',
								size : '120px'
							}

					];

					$("#chartListGrd").jqGrid({
						url : "",
						datatype : "local",
						mtype : "POST",
						shrinkToFit : false,
						scroll : true,
						rownumWidth : true,
						resizable : true,
						rowNum : 40,
						loadonce : true,
						fixed : true,
						viewrecords : true,
						colModel : grdInfoCM,
						onSelectRow : function(rowId) {
							var selRowData = $(this)
									.jqGrid("getRowData", rowId);
							DocBean.buttons.clearBtn.clickFnc();
							showChart(selRowData, true,'Y');
							$('#queryDialog').modal("hide");
						}
					});

				}
			}

		}
	};

	// $("#main #chartList ul li").click(function() {

	function setFilterCondition(pointArray) {
		var i, point, cusIdMap, mdlIdMap, woIdMap, lotIdMap, opeIdMap, toolIdMap;
		var cusId, mdlId, woId, lotId, pToolId, pOpeId;

		cusId = $("#cusIdSel").val();
		mdlId = BaseFnc.returnSpace($("#mdlIdSel").val());
		woId = $("#woIdSel").val();
		lotId = $("#lotIdSel").val();
		pToolId = $("#eqptIdSel").val();
		pOpeId = $("#opeIdSel").val();

		cusIdMap = {};
		mdlIdMap = {};
		woIdMap = {};
		lotIdMap = {};
		opeIdMap = {};
		toolIdMap = {};

		$("#mdlIdSel").empty();
		$("#mdlIdSel").append("<option value=''> </option>");

		for (i = 0; i < pointArray.length; i++) {
			point = pointArray[i];
			if (point.cus_id_fk)
				cusIdMap[point.cus_id_fk] = point.cus_id_fk;
			if (point.wo_id_fk)
				// woIdMap[wo_id_fk] = point.wo_id_fk;
				woIdMap[point.wo_id_fk] = point.wo_id_fk; // NO.03
			if (point.lot_id_fk)
				// lotIdMap[lot_id_fk] = point.lot_id_fk;
				lotIdMap[point.lot_id_fk] = point.lot_id_fk; // NO.03
			if (point.mdl_id_fk)
				mdlIdMap[point.mdl_id_fk] = point.mdl_id_fk;
			if (point.p_ope_id_fk)
				opeIdMap[point.p_ope_id_fk] = point.p_ope_id_fk;
			if (point.p_tool_id_fk)
				toolIdMap[point.p_tool_id_fk] = point.p_tool_id_fk;
		}

		// mdl id special process
		for (var pro in mdlIdMap) {
			var tmpMdlId = mdlIdMap[pro];
			var mdlIdFormated = BaseFnc.replaceSpace(tmpMdlId);
			$("#mdlIdSel").append("<option value= " + mdlIdFormated + ">"
					+ tmpMdlId + "</option>");
		}

		$("#mdlIdSel").val(BaseFnc.replaceSpace(mdlId));

		setSelectionByMap($("#cusIdSel"), cusIdMap, cusId);
		setSelectionByMap($("#opeIdSel"), opeIdMap, pOpeId);
		setSelectionByMap($("#eqptIdSel"), toolIdMap, pToolId);
		setSelectionByMap($("#lotIdSel"), lotIdMap, lotId); // NO.03
		setSelectionByMap($("#woIdSel"), woIdMap, woId); // NO.03
	}

	function setSelectionByMap($domObj, map, originValue) {
		$domObj.empty();
		$domObj.append("<option option=''> </optoin>");
		for (var pro in map) {
			$domObj.append("<option value= " + map[pro] + ">" + map[pro]
					+ "</option>");
		}
		if (typeof(originValue) !== "undefined") {
			$domObj.val(originValue);
		}
	}


	function showChart(selectChartGridData, setConditionFlg,firstFlg) {
		var chartTyp, dataCnt;
		var iary = {
            col_typ_fk : selectChartGridData.col_typ_fk,
            grp_no_fk : selectChartGridData.grp_no_fk,
            chart_no : selectChartGridData.chart_no,
		};
		var querySettingObj = {
			trx_id :"FQPCHTMN",
			action_flg:"I",
			iary : [iary]
		};
		GlobalBean.selectedChart.col_typ = selectChartGridData.col_typ_fk;
		GlobalBean.selectedChart.grp_no = selectChartGridData.grp_no_fk;
		GlobalBean.selectedChart.chart_no = selectChartGridData.chart_no;
		GlobalBean.selectedChart.chart_typ = selectChartGridData.chart_typ;

//		var url = "querySPCChartSettingByCrit";
//		var outTrxObj = comSendAjax(_POST, url, querySettingObj).outPo;
		var outTrxObj = comTrxSubSendPostJson(querySettingObj);
		
		var chartSettingOary = outTrxObj.oaryB;
		var dataArray = new Array();
		var summaryObj = {};
		for (var i = 0; i < chartSettingOary.length; i++) {
			// for(var i=0;i<1;i++){
			var data = new Object();
			data.upl = chartSettingOary[i].chart_upl;
			data.usl = chartSettingOary[i].chart_usl;
			data.ucl = chartSettingOary[i].chart_ucl;
			data.target = chartSettingOary[i].chart_target;
			data.lcl = chartSettingOary[i].chart_lcl;
			data.lsl = chartSettingOary[i].chart_lsl;
			data.lpl = chartSettingOary[i].chart_lpl;
			data.cname = chartSettingOary[i].chart_name;
			data.ctitle = chartSettingOary[i].chart_dsc;
			data.chart_typ = chartSettingOary[i].chart_typ_fk;
			data.gname = chartSettingOary[i].grp_name;

			chartTyp = chartSettingOary[i].chart_typ_fk;

			data.point = new Array();
			// 查询 chart_data
			var queryObj2 = {
				trx_id :"XPCCHTDT",
				action_flg:"L",
				col_typ : selectChartGridData.col_typ_fk,
				grp_no : selectChartGridData.grp_no_fk,
				chart_no : selectChartGridData.chart_no,
				chart_typ : chartSettingOary[i].chart_typ_fk,
                first_flg : firstFlg
			};
			if (selectChartGridData.cus_id) {
				queryObj2.cus_id = selectChartGridData.cus_id;
			}
			if (selectChartGridData.mdl_id) {
				queryObj2.mdl_id = selectChartGridData.mdl_id;
			}
			if (selectChartGridData.wo_id) {
				queryObj2.wo_id = selectChartGridData.wo_id;
			}
			/*if (selectChartGridData.lot_id) {
				queryObj2.lot_id = selectChartGridData.lot_id;
			}*/
			if (selectChartGridData.p_tool_id) {
				queryObj2.p_tool_id = selectChartGridData.p_tool_id;
			}
			if (selectChartGridData.p_ope_id) {
				queryObj2.p_ope_id = selectChartGridData.p_ope_id;
			}
			if (selectChartGridData.input_timestamp_from) {
				queryObj2.input_timestamp_from = selectChartGridData.input_timestamp_from;
			}
			if (selectChartGridData.input_timestamp_to) {
				queryObj2.input_timestamp_to = selectChartGridData.input_timestamp_to;
			}
//			queryObj2.limit_flg = limitFlg ? "Y" : "N" ;
		    
			queryObj2.limit_flg = "Y";
			queryObj2.count = 200;
			// queryObj2.limit_flg = limitFlg ? "Y" : "N";
//			var url = "queryChartDataByCrit";
//			var outTrxObj2 = comSendAjax(_POST, url, queryObj2);
			var outTrxObj2 = comTrxSubSendPostJson(queryObj2);
			if (outTrxObj2.rtn_code != _NORMAL) {
				// TODO
				alert("查询失败" + outTrxObj2.rtn_mesg);
				return false;
			}

			var dataList = outTrxObj2.oary2;

			var tempDataCnt = dataList.length < 200 ? dataList.length : 200;// add
			// point
			// toplimit
			// ---bailang
			if (selectChartGridData.input_timestamp_from) {
				tempDataCnt = dataList.length;
			}
			for (var j = 0; j < tempDataCnt; j++) {
				// for (var j = 0; j < dataList.length; j++) {
				var point = new Object();
				var chartData = dataList[j];

				point.inputTimestamp = chartData.input_timestamp;
				// point.value = Math.ceil(Math.random() * 200 + 150);
				point.value = chartData.chart_value;
				point.glassId = chartData.prd_seq_id_fk;
				point.processEqptId = chartData.p_tool_id_fk;
				point.measurementEqptId = chartData.m_tool_id_fk;
				point.comment = chartData.chart_comment;
				point.reporter = chartData.evt_usr;
				point.chart_rule1_rlt_fk = chartData.chart_rule1_rlt_fk;
				point.chart_spec_rlt_fk = chartData.chart_rule1_rlt_fk;
				point.proc_timestamp = chartData.proc_timestamp; // NO.03
				point.wo_id_fk = chartData.wo_id_fk;
				point.cus_id_fk = chartData.cus_id_fk;
				point.so_id_fk = chartData.so_id_fk;
				/*point.lot_id_fk = chartData.lot_id_fk;*/
				point.chart_rule_1_rlt = chartData.chart_rule1_rlt_fk;
				point.col_typ_fk = chartData.col_typ_fk;
				point.grp_no_fk = chartData.grp_no_fk;
				point.chart_no_fk = chartData.chart_no_fk;
				point.chart_typ_fk = chartData.chart_typ_fk;
				point.input_time_d = chartData.input_time_d;
				point.ucl = chartData.chart_ucl_fk;
				point.lcl = chartData.chart_lcl_fk;


				point = $.extend(point, chartData);
				// liufang add median chart
				if (chartTyp == "01" || chartTyp == '30') {
					//MEAN                  //MEDIAN
					point.rawData = dataList[j].rawDataList;
					point.rawDataList = dataList[j].rawDataList;
				}
				data.point.push(point);
			}

			if (chartTyp == "01" || chartTyp == "10" || chartTyp == '30'
					|| chartTyp == '40' || chartTyp == '50' || chartTyp == '60') {
				if (setConditionFlg == true) {
					setFilterCondition(dataList);
					GlobalBean.displayChartPointCount = data.point.length;
				}
				if (chartTyp === "01") {
					clearRawDataGrd();
					fillRawDataGrd(data.point, data.usl, data.lsl);
				} else {
					clearRawDataGrd();
				}
				fillChatDataGrd(data.point);
				summaryObj.mainChartSetting = chartSettingOary[i];
				summaryObj.mainChartPointArr = data.point;
			} else {
				fillChartDataGrdBySlaveChartData(data.point);
				summaryObj.slaveChartSetting = chartSettingOary[i];
				summaryObj.slaveChartPointArr = data.point;
			}
			dataArray.push(data);
			GlobalBean.displayChartCount++;
		}

		fillSummaryDataGrd(summaryObj);

		$(this).toggleClass("chartListSelectedBackgroundColor");

		switch (GlobalBean.displayChartCount) {

			case 1 :
				var chart = new Chart();
                var key = {
                    chart01 : dataArray[0].chart_typ,
                    chart01V: dataArray[0],
                    k : 'N',
                    ucl : dataArray[0].ucl,
                    lcl : dataArray[0].lcl
                };
				chart.initializeCanvas("chart", 1222, 550, false,
						dataArray[0].point.length);
				chart.initializeChart(dataArray[0], 1, 1);
				if(typeof(dataArray[0].ucl)=="undefined" && dataArray[0].point.length > 25){
                    key.k = 'UN';
                    chart.drawCL();
				}
                if(document.getElementById("svgdiv").childNodes.length != 0){
                    var list = document.getElementById("svgdiv");
                    list.removeChild(list.childNodes[0]);
                }
                if(dataArray[0].point.length >= 30){//样本数至少为30才画直方图
                    chart.histogram(key);
                }
				chart.drawPoint();
				chart.activateClickEvent();
				break;

			case 2 :
				var chart1 = new Chart();
				var key = {
					chart01 : dataArray[0].chart_typ,
					chart02: dataArray[1].chart_typ,
					chart01V: dataArray[0],
					chart02V: dataArray[1],
					k : 'N',
					ucl : dataArray[0].ucl,
					lcl : dataArray[0].lcl
				};
				// setCanvasWidth(dataArray[0].point.length);
				chart1.initializeCanvas("chart", 1222, 550, false,
						dataArray[0].point.length);
				chart1.initializeChart(dataArray[0], 2, 1);

                if(typeof(dataArray[0].ucl)=="undefined" && dataArray[0].point.length > 25){
                	key.k = 'UN';
                    chart1.drawCL();
                }
                //如果存在则删除原来的直方图
                if(document.getElementById("svgdiv").childNodes.length != 0){
                    var list = document.getElementById("svgdiv");
                    list.removeChild(list.childNodes[0]);
                }
                if(dataArray[0].point.length >= 30){//样本数至少为30才画直方图
                    chart1.histogram(key);
				}
				chart1.drawPoint();
				/*chart1.activateClickEvent();*/

				// fix bug
				var chart2 = new Chart();
				// setCanvasWidth(dataArray[0].point.length);
				chart2.initializeCanvas("chart", 1222, 550, true,
						dataArray[0].point.length);
				chart2.initializeChart(dataArray[1], 2, 2);
				chart2.drawPoint();
				// chart2.activateClickEvent();
				GlobalBean.page.addChart(chart1);
				GlobalBean.page.addChart(chart2);
				GlobalBean.page.activateClickEvent();
				break;

			case 3 :
				var chart1 = new Chart();
                var key = {
                    chart01 : dataArray[0].chart_typ,
                    chart02: dataArray[1].chart_typ,
                    chart01V: dataArray[0],
                    chart02V: dataArray[1],
                    k : 'N',
                    ucl : dataArray[0].ucl,
                    lcl : dataArray[0].lcl
                };
				chart1.initializeCanvas("chart", 1222, 550, false,
						dataArray[0].point.length);
				chart1.initializeChart(dataArray[0], 3, 1);
                if(typeof(dataArray[0].ucl)=="undefined" && dataArray[0].point.length > 25){
                    key.k = 'UN';
                    chart1.drawCL();
                }
                //如果存在则删除原来的直方图
                if(document.getElementById("svgdiv").childNodes.length != 0){
                    var list = document.getElementById("svgdiv");
                    list.removeChild(list.childNodes[0]);
                }
                if(dataArray[0].point.length >= 30){//样本数至少为30才画直方图
                    chart1.histogram(key);
                }
				chart1.drawPoint();

				var chart2 = new Chart();
				chart2.initializeCanvas("chart", 1222, 550, true,
						dataArray[0].point.length);
				chart2.initializeChart(dataArray[1], 3, 2);
				chart2.drawPoint();

				var chart3 = new Chart();
				chart3.initializeCanvas("chart", 1222, 550, true,
						dataArray[0].point.length);
				chart3.initializeChart(dataArray[2], 3, 3);
				chart3.drawPoint();

				GlobalBean.page.addChart(chart1);
				GlobalBean.page.addChart(chart2);
				GlobalBean.page.addChart(chart3);
				GlobalBean.page.activateClickEvent();
				break;
		}
	}

	DocBean.grids.chartGrid.initFnc();

	DocBean.buttons.clearBtn.ID.click(DocBean.buttons.clearBtn.clickFnc);

	DocBean.buttons.queryBtn.ID.click(DocBean.buttons.queryBtn.clickFnc);

	DocBean.buttons.calcCPKBtn.ID.click(DocBean.buttons.calcCPKBtn.calcCpkFnc);

	DocBean.buttons.refreshBtn.ID.click(DocBean.buttons.refreshBtn.clickFnc);

	//直方图分析按钮
	$("#analysis_btn").click(function () {
        $("#histogramDialog").modal({
            backdrop : true,
            keyboard : false,
            show : false
        });
        $("#histogramDialog").modal("show");
        }
	);

	$("#f11_btn").click(function() {
		var chartDatas = [];
		var summaryDatas = [];
		var rawDatas = [];

		var col_typ, grp_no, chart_no, chart_typ;

		var cusId, mdlId, woId, lotId, pToolId, pOpeId, fromTime, endTime, reportBeginDate, reportBeginTime, reportEndDate, reportEndTime, reportBeginTimestamp, reportEndTimestamp;

		col_typ = GlobalBean.selectedChart.col_typ;
		grp_no = GlobalBean.selectedChart.grp_no;
		chart_no = GlobalBean.selectedChart.chart_no;
		chart_typ = GlobalBean.selectedChart.chart_typ;

		$("#rawDataTbl tr").each(function(i, tr) {
					var raw = [];
					$(tr).find("td,th").each(function(j, td) {
								raw.push($(td).text());
							})

					rawDatas.push(raw);
				});

		$("#chartDataTbl tr").each(function(i, tr) {
					var chartData = [];
					$(tr).find("td,th").each(function(j, td) {
								chartData.push($(td).text());
							})
					chartDatas.push(chartData);
				})

		$("#summaryTbl tr").each(function(i, tr) {
					var summaryData = [];
					$(tr).find("td,th").each(function(j, td) {
								summaryData.push($(td).text());
							})
					summaryDatas.push(summaryData);
				})

		cusId = $("#cusIdSel").val();
		mdlId = BaseFnc.returnSpace($("#mdlIdSel").val());
		woId = $("#woIdSel").val();
		/*lotId = $("#lotIdSel").val();*/
		pToolId = $("#eqptIdSel").val();
		pOpeId = $("#opeIdSel").val();

		// 添加时间的防呆 ， 选日期同时必须选时间
		reportBeginDate = $("#reportBeginDatepicker input").val();
		reportBeginTime = $("#reportBeginTimepicker input").val();
		reportEndDate = $("#reportEndDatepicker input").val()
		reportEndTime = $("#reportEndTimepicker input").val();
		if ((!reportBeginDate && reportBeginTime)
				|| (reportBeginDate && !reportBeginTime)) {
			showErrorDialog("", "开始日期和时间必须同时选择");
			return false;
		}
		if ((!reportEndDate && reportEndTime)
				|| (reportEndDate && !reportEndTime)) {
			showErrorDialog("", "结束日期和时间必须同时选择");
			return false;
		}
		// 时间前面增加checkbox，判定是否增加时间条件
		if ($("#reportBeginTimestampChk").attr("checked") === "checked") {
			if (!reportBeginDate || !reportBeginTime) {
				showErrorDialog("", "请选择上报开始时间");
				return false;
			}
			reportBeginTimestamp = reportBeginDate + " " + reportBeginTime;
		}
		if ($("#reportEndSTimestampChk").attr("checked") === "checked") {
			if (!reportEndDate || !reportEndTime) {
				showErrorDialog("", "请选择上报结束时间")
				return false;
			}
			reportEndTimestamp = reportEndDate + " " + reportEndTime;
		}

		// console.info(reportBeginTimestamp + ", " + reportEndTimestamp);

		var inObj = {
			col_typ_fk : GlobalBean.selectedChart.col_typ,
			grp_no_fk : GlobalBean.selectedChart.grp_no,
			chart_no : GlobalBean.selectedChart.chart_no
		};

		// fix for export excel's inTrx missing chart_typ;
		inObj.chart_typ = GlobalBean.selectedChart.chart_typ;

		if (cusId) {
			inObj.cus_id = cusId;
		}
		if (mdlId) {
			inObj.mdl_id = mdlId;
		}
		if (woId) {
			inObj.wo_id = woId;
		}
		/*if (lotId) {
			inObj.lot_id = lotId;
		}*/
		if (pToolId) {
			inObj.p_tool_id = pToolId;
		}
		if (pOpeId) {
			inObj.p_ope_id = pOpeId;
		}
		if (reportBeginTimestamp) {
			inObj.input_timestamp_from = reportBeginTimestamp;
		}
		if (reportEndTimestamp) {
			inObj.input_timestamp_to = reportEndTimestamp;
		}

		var str = '<form id= "exportExcelForm" style="position:display;z-index:-1122;" method="post" action="exportChartData.do">';
		str = str + "<input id='rawDataTxt' type='hidden' name = 'rawData' / >";
		str = str
				+ "<input id='chartDataTxt' type='hidden'  name = 'chartData'/>";
		str = str
				+ "<input id='summaryDataTxt' type='hidden'  name = 'summaryData' />";
		str = str + "<input id='colTypTxt' type='hidden'  name = 'col_typ' />";
		str = str + "<input id='grpNoTxt' type='hidden'  name = 'grp_no' />";
		str = str
				+ "<input id='chartNoTxt' type='hidden'  name = 'chart_no' />";
		str = str
				+ "<input id='chartTypTxt'ype='hidden'  name = 'chart_typ' />";
		str = str + "<input id='cusIdTxt' type='hidden'  name = 'cus_id' />";
		str = str + "<input id='mdlIdTxt' type='hidden'  name = 'mdl_id' />";
		str = str + "<input id='woIdTxt' type='hidden'  name = 'wo_id' />";
		/*str = str + "<input id='lotIdTxt' type='hidden'  name = 'lot_id' />";*/
		str = str + "<input id='pToolId' type='hidden'  name = 'p_tool_id' />";
		str = str + "<input id='pOpeId' type='hidden'  name = 'p_ope_id' />";
		str = str
				+ "<input id='inputTimestampFromTxt' type='hidden'  name = 'input_timestamp_from' />";
		str = str
				+ "<input id='inputTimestampToTxt' type='hidden'  name = 'input_timestamp_to' />";
		str = str + "<input id='limitFlgTxt' type='hidden' name = 'limitFlg'  value='N' / >";		
		str = str + "</form>";

		if ($("#exportExcelForm").length > 0) {
			$("#exportExcelForm").remove();
		}
		$(str).appendTo("body");
		$("#rawDataTxt").val(JSON.stringify(rawDatas));
		$("#chartDataTxt").val(JSON.stringify(chartDatas));
		$("#summaryDataTxt").val(JSON.stringify(summaryDatas));
		if($("#rawDataTxt").val().length == 2
			&& $("#chartDataTxt").val().length == 2
			&& $("#summaryDataTxt").val().length == 2){
            $("#exportExcelForm").remove();
            showErrorDialog("", "没有数据可以导出，请重新选择！");
            return false;
		}

		$("#colTypTxt").val(GlobalBean.selectedChart.col_typ)
		$("#grpNoTxt").val(GlobalBean.selectedChart.grp_no)
		$("#chartNoTxt").val(GlobalBean.selectedChart.chart_no)
		$("#chartTypTxt").val(GlobalBean.selectedChart.chart_typ)
		$("#cusIdTxt").val(cusId);
		$("#mdlIdTxt").val(mdlId);
		$("#woIdTxt").val(woId);
		/*$("#lotIdTxt").val(lotId);*/
		$("#pToolId").val(pToolId);
		$("#pOpeId").val(pOpeId);
		$("#inputTimestampFromTxt").val(reportBeginTimestamp);
		$("inputTimestampToTxt").val(reportEndTimestamp);

		$("#exportExcelForm").submit();
			// var col_typ, grp_no, chart_no, chart_typ;
			//
			// col_typ = GlobalBean.selectedChart.col_typ;
			// grp_no = GlobalBean.selectedChart.grp_no;
			// chart_no = GlobalBean.selectedChart.chart_no;
			// chart_typ = GlobalBean.selectedChart.chart_typ;
        $("#exportExcelForm").remove();
	});
	var BaseFnc = {
		replaceSpace : function(str) {
			if (!str) {
				return str;
			}
			return str.replace(/[ ]/g, "@");
		},
		returnSpace : function(str) {
			if (!str) {
				return str;
			}
			return str.replace(/[@]/g, " ");
		}
	};

	$("#reportBeginDatepicker").hide();
	$("#reportBeginTimepicker").hide();
	$("#reportEndDatepicker").hide();
	$("#reportEndTimepicker").hide();

	$("#reportBeginTimestampChk").click(function() {
				if ($(this).attr("checked") == "checked") {
					$("#reportBeginDatepicker").show();
					$("#reportBeginTimepicker").show();
				} else {
					$("#reportBeginDatepicker").hide();
					$("#reportBeginTimepicker").hide();
				}
			})
	$("#reportEndSTimestampChk").click(function() {
				if ($(this).attr("checked") == "checked") {
					$("#reportEndDatepicker").show();
					$("#reportEndTimepicker").show();
				} else {
					$("#reportEndDatepicker").hide();
					$("#reportEndTimepicker").hide();
				}
			})

	function filterChartFnc(cusId, mdlId, woId, lotId, pToolId, pOpeId, reportBeginTimestamp, reportEndTimestamp) {
		var inObj = {
			col_typ_fk : GlobalBean.selectedChart.col_typ,
			grp_no_fk : GlobalBean.selectedChart.grp_no,
			chart_no : GlobalBean.selectedChart.chart_no
		};

		DocBean.buttons.clearBtn.clickFnc();
		if (cusId) {
			inObj.cus_id = cusId;
		}
		if (mdlId) {
			inObj.mdl_id = mdlId;
		}
		if (woId) {
			inObj.wo_id = woId;
		}
		/*if (lotId) {
			inObj.lot_id = lotId;
		}*/
		if (pToolId) {
			inObj.p_tool_id = pToolId;
		}
		if (pOpeId) {
			inObj.p_ope_id = pOpeId;
		}
		if (reportBeginTimestamp) {
			inObj.input_timestamp_from = reportBeginTimestamp;
		}
		if (reportEndTimestamp) {
			inObj.input_timestamp_to = reportEndTimestamp;
		}
		DocBean.buttons.clearBtn.clickFnc();
		// fix for export excel's inTrx missing chart_typ;
		inObj.chart_typ = GlobalBean.selectedChart.chart_typ;
		showChart(inObj, true, false);
	}
	$("#f2_filter_btn").click(function() {
		var cusId, mdlId, woId, lotId, pToolId, pOpeId, fromTime, endTime, reportBeginDate, reportBeginTime, reportEndDate, reportEndTime, reportBeginTimestamp, reportEndTimestamp;

		cusId = $("#cusIdSel").val();
		mdlId = BaseFnc.returnSpace($("#mdlIdSel").val());
		woId = $("#woIdSel").val();
		//lotId = $("#lotIdSel").val();
		pToolId = $("#eqptIdSel").val();
		pOpeId = $("#opeIdSel").val();

		// 当没有管制图显示时，不能进行筛选
		if (GlobalBean.displayChartCount <= 0) {
			showErrorDialog("", "当前没有可以被筛选的管制图");
			return false;
		}

		// 添加时间的防呆 ， 选日期同时必须选时间
		reportBeginDate = $("#reportBeginDatepicker input").val();
		reportBeginTime = $("#reportBeginTimepicker input").val();
		reportEndDate = $("#reportEndDatepicker input").val()
		reportEndTime = $("#reportEndTimepicker input").val();
		if ((!reportBeginDate && reportBeginTime)
				|| (reportBeginDate && !reportBeginTime)) {
			showErrorDialog("", "开始日期和时间必须同时选择");
			return false;
		}
		if ((!reportEndDate && reportEndTime)
				|| (reportEndDate && !reportEndTime)) {
			showErrorDialog("", "结束日期和时间必须同时选择");
			return false;
		}
		// 时间前面增加checkbox，判定是否增加时间条件
		if ($("#reportBeginTimestampChk").attr("checked") === "checked") {
			if (!reportBeginDate || !reportBeginTime) {
				showErrorDialog("", "请选择上报开始时间");
				return false;
			}
			reportBeginTimestamp = reportBeginDate + " " + reportBeginTime;
		}
		if ($("#reportEndSTimestampChk").attr("checked") === "checked") {
			if (!reportEndDate || !reportEndTime) {
				showErrorDialog("", "请选择上报结束时间")
				return false;
			}
			reportEndTimestamp = reportEndDate + " " + reportEndTime;
		}

		filterChartFnc(cusId, mdlId, woId, lotId, pToolId, pOpeId, reportBeginTimestamp, reportEndTimestamp);

	})

	function iniDateTimePicker() {
		var datepickerBeginDate, datepickerBeginTime, datepickerEndDate, datepickerEndTime;
		$("#reportBeginDatepicker,#reportEndDatepicker,#filterChartDialog_reportBeginDatepicker,#filterChartDialog_reportEndDatepicker")
				.datetimepicker({
							language : 'zh-CN',
							pickTime : false,
				            weekStart: 1,
				            autoclose: true,
				            orientation:'right',
						});
		$("#reportBeginTimepicker,#reportEndTimepicker,#filterChartDialog_reportBeginTimepicker,#filterChartDialog_reportEndTimepicker")
				.datetimepicker({
							language : 'zh-CN',
							pickDate : false
						});
		datepickerBeginDate = $("#reportBeginDatepicker")
				.data("datetimepicker");
		datepickerBeginDate.setLocalDate(datepickerBeginDate.getLocalDate());

		datepickerBeginTime = $("#reportBeginTimepicker")
				.data("datetimepicker");
		datepickerBeginTime.setLocalDate(new Date());

		datepickerEndDate = $("#reportEndDatepicker").data("datetimepicker");
		datepickerEndDate.setLocalDate(datepickerEndDate.getLocalDate());

		datepickerEndTime = $("#reportEndTimepicker").data("datetimepicker");
		datepickerEndTime.setLocalDate(new Date());
	}
	iniDateTimePicker();

	function fillChartDataGrdBySlaveChartData(pointArr) {
		var i, point, row3, pointCnt;
		var str = "<tr><td>子图点值</td>";

		pointCnt = pointArr.length;

		for (i = 0; i < pointCnt; i++) {
			point = pointArr[i];
			str += "<td>" + point.value.toFixed(3) + "</td>";
		}

		str += "</tr>";
		$(str).appendTo("#chartDataTbl tbody");
	}
	function fillChatDataGrd(pointArr) {
		var i, j, pointCnt, columns, point, rawArr, obj, raw, row1, row2, row3, rawValue, str;
		pointCnt = pointArr.length;

		var theadStr = '';
		var row1Str = "<td>原始值求和</td>", row2Str = "<td  style='width:80px'>主图点值</td>", row3Str = "<td style='width:100px'>子图点值</td>";
		for (i = 0; i < pointCnt; i++) {
			theadStr += '<th>' + (i + 1) + '</th>'
			point = pointArr[i];
			rawArr = point.rawData;
			if (rawArr) {
				rawValue = 0;
				for (j = 0; j < rawArr.length; j++) {
					raw = rawArr[j];
					rawValue = rawValue + raw.prd_raw_value;
				}
				row1Str += "<td>" + rawValue.toFixed(3) + "</td>";

			}
			row2Str += "<td>" + point.value.toFixed(3) + "</td>"
		}
		// str = '<div id="chartDataDiv" class="span12">
		str = '<fieldset>管制图数据</fieldset>';
		str += ' <table  id="chartDataTbl" class="table table-bordered table-condensed" ><thead><th><div style="width:100px"></div></th>'
				+ theadStr + '</thead>';
		str += "<tbody><tr>" + row1Str + "</tr>";
		str += "<tr>" + row2Str + "</tr></tbody></table>";
		$("#chartDataDiv").empty();
		// if ($("#chartDataDiv").length > 0) {
		// $("#chartDataDiv").remove();
		// }
		$(str).appendTo("#chartDataDiv");
	}

	function clearRawDataGrd() {
		$("#rawDataDiv").empty();
	}
	function fillRawDataGrd(pointArr, usl, lsl) {
		var i, columns, rows = [], rawArr, row, point, str, pointCnt = pointArr.length;
		var str, headStr, bodyStr = "", rowStr;

		headStr = buildRawDataHeadStr(pointCnt);
		if (!headStr) {
			return false
		}

		bodyStr = buildRawDataRowStr(pointArr, usl, lsl);
		if (!bodyStr) {
			return false;
		}
		str = '<fieldset>原始数据</fieldset> ';
		str += '<table id="rawDataTbl"  class="table table-bordered table-condensed"><thead>';
		str += headStr + '</thead>';
		str += '<tbody>' + bodyStr + '</tbody>';
		str += '</table>';
		if ($("#rawDataTbl").length > 0) {
			$("#rawDataTbl").remove();
		}
		$("#rawDataDiv").append(str);
		// console.info(str);
		// console.info($("#rawDataDiv").html());

		// DocBean.grids.rawDataGrd.initFnc(columns, rows);

	}

	// 将一组rawData组成一行 并返回
	function buildRawDataRowStr(pointArr, usl, lsl) {
		var str = "", raw, i, j, pointCnt = pointArr.length, rawDataCnt, maxRawDataCnt;

		var rawDataCnt = 0;
		maxRawDataCnt = 0;
		if (pointCnt <= 0) {
			return false;
		}

		for (i = 0; i < pointArr.length; i++) {
			if (pointArr[i].rawData) {
				rawDataCnt = pointArr[i].rawData.length;
				if (rawDataCnt > maxRawDataCnt) {
					maxRawDataCnt = rawDataCnt;
				}
			}
		}

		if (maxRawDataCnt <= 0) {
			return false;
		}

		// add tr : prd_seq_id
		str = str + "<tr><td>玻璃ID</td>";
		for (i = 0; i < pointCnt; i++) {
			var point = pointArr[i];
			if (isOOS(point.value, point.chart_typ_fk, usl, lsl)) {
				str += "<td style ='color:red' >" + point.glassId + "</td>";
			} else {
				str += "<td>" + point.glassId + "</td>";
			}

		}
		str = str + "</tr>";

		for (i = 0; i < maxRawDataCnt; i++) {
			str = str + "<tr><td>" + (i + 1) + "</td>";
			for (j = 0; j < pointCnt; j++) {
				var point = pointArr[j];
				console.info(point);
				var rawData = point ? point.rawData : null;
				console.info(rawData);

				raw = (rawData && $.isArray(rawData) && rawData.length > i - 1)
						? rawData[i]
						: null;

				if (raw) {
					if (isOOS(raw.prd_raw_value, pointArr[j].chart_typ_fk, usl,
							lsl)) {
						str += "<td style ='color:red'>" + raw.prd_raw_value
								+ "</td>";
					} else {
						str += "<td>" + raw.prd_raw_value + "</td>";
					}
				} else {
					str += "<td></td>";
				}
			}
			str += "</tr>";
		}

		return str;
	}

	function buildRawDataHeadStr(pointCnt) {
		var str = "<thead><th></th>";
		if (pointCnt <= 0) {
			return null;
		}
		for (i = 0; i < pointCnt; i++) {
			str += "<th>" + (i + 1) + "</th>";
		}
		str += "</thead>";
		return str;
	}

	function fillSummaryDataGrd(summaryObj) {

		var str, bodyStr = "";
		var ca, cp, cpu, cpl, cpk, pp, ppk, mainTarget, grade, totalSampleCnt, totalGroupCnt, rawDataCnt;
		var totalSampleValue, totalMainChartValue, totalSlaveValue, averageMainChartValue, averageSlaveChartValue;
		var sigma, mainUsl, mainLsl, mainUcl, mainLcl, slaveUcl, slaveLcl;
		var mainPoint, i, j, raw, slavePoint;
		var mainChartSetting = summaryObj.mainChartSetting, slaveChartSetting = summaryObj.slaveChartSetting;
		var mainChartPointArr = summaryObj.mainChartPointArr, slaveChartPointArr = summaryObj.slaveChartPointArr;
		// var pointCnt = mainChartPointArr.length, slavePointCnt =
		// slaveChartPointArr.length;
		var pointCnt = mainChartPointArr.length, slavePointCnt;

		if (mainChartSetting.chart_typ_fk === "40"
				|| mainChartSetting.chart_typ_fk === "50"
				|| mainChartSetting.chart_typ_fk === "60"
            	|| mainChartSetting.chart_typ_fk === "10" ) {
			slavePointCnt = 0;
			if (!mainChartSetting || !mainChartPointArr) {
				return false;
			}
			slaveUcl = 0;
			slaveLcl = 0;

		} else {
			slavePointCnt = slaveChartPointArr.length;
			if (!mainChartSetting || !slaveChartSetting || !mainChartPointArr
					|| !slaveChartPointArr) {
				return false;
			}
			slaveUcl = slaveChartSetting.chart_ucl;
			slaveLcl = slaveChartSetting.chart_lcl;
		}

		// 总样本数
		totalSampleCnt = pointCnt;

		mainUsl = mainChartSetting.chart_usl;
		mainLsl = mainChartSetting.chart_lsl;
		if(typeof (mainChartSetting.chart_ucl) == "undefined"){
			if(mainChartPointArr.length > 25){
                mainUcl =  mainChartPointArr[mainChartPointArr.length-1].chart_ucl_fk.toFixed(2);
			}
			/*if(typeof (mainChartPointArr[mainChartPointArr.length-1].chart_ucl_fk) !== "undefined"){

			}*/
		}else{
            mainUcl = mainChartSetting.chart_ucl;
		}

		if(typeof (mainChartSetting.chart_lcl) == "undefined"){
            if(mainChartPointArr.length > 25){
                mainLcl = mainChartPointArr[mainChartPointArr.length-1].chart_lcl_fk.toFixed(2);
            }
			/*if(typeof (mainChartPointArr[mainChartPointArr.length-1].chart_lcl_fk) !== "undefined"){

			}*/
		}else{
            mainLcl = mainChartSetting.chart_lcl;
		}

		mainTarget = mainChartSetting.chart_target;

		totalSampleValue = 0;
		totalMainChartValue = 0;
		totalSlaveValue = 0;

		for (i = 0; i < pointCnt; i++) {
			mainPoint = mainChartPointArr[i];
			var chartTyp = mainChartSetting.chart_typ_fk;

			if (chartTyp === "01" || chartTyp === "30") {

				rawArr = mainPoint.rawData;
				// 组内数
				rawDataCnt = $.isArray(rawArr) ? rawArr.length : 0;
				if (rawArr && rawDataCnt > 0) {
					for (j = 0; j < rawDataCnt; j++) {
						raw = rawArr[j];

						// 总主图值：所有mean点加总
						totalMainChartValue += raw.prd_raw_value;
					}
				}

			}

			// 总样本值
			totalSampleValue += mainPoint.value;

		}

		if (slavePointCnt != 0) {
			// 总子图值 : 子图所有点加总
			for (i = 0; i < slaveChartPointArr.length; i++) {
				slavePoint = slaveChartPointArr[i];
				totalSlaveValue += slavePoint.value;
			}

		} else {
			totalSlaveValue = 0;
		}
		// 总组数 = 总样本数 * 组内数
		totalGroupCnt = totalSampleCnt * rawDataCnt;

		// 主图均值 = 总样本值/总样本数
		averageMainChartValue = totalSampleValue / totalSampleCnt;

		// 子图均值 ＝ 总子图值/样本总数
		averageSlaveChartValue = totalSlaveValue / totalSampleCnt;

		// ca = (实际均值 - 中心值) / (t/2) --- t = (usl - lsl)
		var t = mainUsl - mainLsl;
		ca = Math.abs((averageMainChartValue - mainTarget) / (t / 2));

		// sigma 标准差
		var avgSum = 0;
		var mean = averageMainChartValue;
		for (i = 0; i < pointCnt; i++) {
			mainPoint = mainChartPointArr[i];
			avgSum += (mainPoint.value - mean) * (mainPoint.value - mean);
		}
		sigma = Math.sqrt(avgSum / (pointCnt - 1));
		cp = t / (6 * sigma);

		cpl = (mean - mainLsl) / (6 * sigma);
		cpu = (mainUsl - mean) / (6 * sigma);

		cpk = cpl > cpu ? cpu : cpl;

		// 计算ppk
		// 计算 sigma_ppk
		var sigma_ppk;
		if (mainChartSetting.chart_typ == "01") {
			var tmpSumSum_ppk = 0;
			for (i = 0; i < pointCnt; i++) {
				point = mainChartPointArr[i];
				var tmpSum_ppk = 0;
				if (point.rawData && $.isArray(point.rawData)) {

					for (j = 0; j < point.rawData.length; j++) {
						raw = point.rawData[j];
						var rawValue = raw.prd_raw_value;
						tmpSum_ppk = tmpSum_ppk
								+ Math.pow((rawValue - mean), 2);
					}

					tmpSumSum_ppk = tmpSumSum_ppk + tmpSum_ppk;
				}
			}
			sigma_ppk = Math.sqrt(tmpSumSum_ppk / (pointCnt * rawDataCnt - 1));

			// 计算 pp
			if (mainUsl != null && mainLsl != null) {
				pp = (mainUsl - mainLsl) / (sigma_ppk * 6);
			} else if (mainUsl = null && mainLsl == null) {
				pp = (mainUsl - mean) / (sigma_ppk * 3);
			} else if (mainUsl == null && mainLsl != null) {
				pp = (mean - mainLsl) / (sigma_ppk * 3);
			}
			// 计算 ppk
			if (mainUsl != null && mainLsl != null) {
				ppk = (1 - Math.abs(ca)) * pp;
			} else {
				ppk = pp;
			}

		} else {
			sigma_ppk = sigma;
			ppk = cpk;
		}

		if (cpk >= 1.67) {
			grade = "A+";
		} else if (cpk >= 1.33) {
			grade = "A";
		} else if (cpk >= 1.00) {
			grade = "B";
		} else if (cpk >= 0.67) {
			grade = "C";
		} else {
			grade = "D";
		}

		bodyStr = "<tr>" + wrapByTd(ca) + wrapByTd(cp) + wrapByTd(cpu)
				+ wrapByTd(cpl) + wrapByTd(cpk) + wrapByTd(pp) + wrapByTd(ppk);
		bodyStr += wrapByTd(grade, false) + wrapByTd(totalSampleCnt, false)
				+ wrapByTd(totalGroupCnt, false) + wrapByTd(rawDataCnt, false);
		bodyStr += wrapByTd(totalSampleValue) + wrapByTd(totalMainChartValue)
				+ wrapByTd(totalSlaveValue);
		bodyStr += wrapByTd(averageMainChartValue)
				+ wrapByTd(averageSlaveChartValue);
		bodyStr += wrapByTd(sigma) + wrapByTd(mainUsl) + wrapByTd(mainLsl)
				+ wrapByTd(mainUcl) + wrapByTd(mainLcl) + wrapByTd(slaveUcl)
				+ wrapByTd(slaveLcl);
		bodyStr += "</tr>";

		str = '<div id="sumaryDiv" class="col-lg-12 col-md-12 col-sm-12" >';
		str += '<fieldset>汇总数据</fieldset>';
		str += '<table id="summaryTbl" class="table table-bordered table-condensed">';
		str += '<thead><th>CA</th><th>CP</th><th>CPU</th><th>CPL</th><th>CPK</th>';
		str += '<th>PP</th><th>PPK</th><th>GRADE</th>';
		str += '<th>总样本数</th><th>总组数</th><th>组内数</th>';
		str += '<th>总样本值</th><th>总主图值</th><th>总子图值</th>';
		str += '<th>主图均值</th><th>子图均值</th>';
		str += '<th>标准差</th><th>主USL</th><th>主LSL</th>';
		str += '<th>主UCL</th><th>主LCL</th><th>子UCL</th><th>子LCL</th></thead>';
		str += '<tbody>'
		str += bodyStr + '</tbody></table></div>';
		if ($("#sumaryDiv").length > 0) {
			$("#sumaryDiv").remove();
		}
        //$("#sumaryDiv").append(str);
		$(str).appendTo("body");
	}

	function wrapByTd(dbl, formatFlg) {
		if (typeof(formatFlg) !== "undefined" && !formatFlg) {
			return "<td>" + dbl + "</td>";
		}
		return "<td>" + formatDouble(dbl) + "</td>";
	}

	function wrapAndFixedByTd(dbl, formatFlg) {
		if (typeof(formatFlg) !== "undefined" && !formatFlg) {
			return "<td>" + dbl + "</td>";
		}
		return "<td>" + formatDouble(dbl) + "</td>";
	}

	function formatDouble(dbl) {
		var strDbl = dbl + "";
		var index = strDbl.indexOf(".");
		if (index === -1) {
			return strDbl + ".000";
		}
		var strRight = strDbl.substr(index + 1);
		var strLeft = strDbl.substr(0, index);
		if (strRight.length > 3) {
			return strDbl.substr(0, index + 4);
		} else {
			return strLeft + "." + ComL2S(strRight, 3, "0")
		}
	}
	function ComL2S(data1, length, data2) {
		if (length <= 0) {
			return null;
		}
		var str = data1.toString();
		if (data1.length > length) {
			return null;
		}
		var size = str.length;
		var chazhi = length - size;
		for (var i = 0; i < chazhi; i++) {
			str = str + data2;
		}
		return str;
	}
	function isOOS(pointValue, chartTyp, usl, lsl) {

		return isMainChart(chartTyp)
				&& ((usl != null && pointValue > usl) || (lsl != null && pointValue < lsl));
	}
	function isBreakRule(ruleRlt, chartTyp) {

		if (isMainChart() && ruleRlt) {
			return ruleRlt.indexOf("Y") == -1 ? false : true;
		}
		return false;
	}
	function isMainChart(chartTyp) {
		return chartTyp == "01" || chartTyp == "10" || chartTyp == '30'
				|| chartTyp == '40' || chartTyp == '50' || chartTyp == '60';
	}

	function sendTxAddSelect(trxId, actionFlg, iary, $selectDom, val, text) {
		var inObj, outObj, tblCnt, oary, i;
		inObj = {
			trx_id : trxId,
			action_flg : actionFlg,
			iary : [iary]
		};
		outObj = comTrxSubSendPostJson(inObj);
		if (outObj.rtn_code === "0000000") {
			tblCnt = outObj.tbl_cnt;
			$selectDom.empty();
			for (i = 0; i < tblCnt; i++) {
				oary = outObj.oary;
				oary = $.isArray(oary) ? oary : [oary];
				SelectDom.addSelect($selectDom, oary[i][val], oary[i][text]);
			}
		}
	}

	var FilterDialog = {
		setCusId : function() {

			var chartDataCondition = GlobalBean.chartDataCondition;
			var i, cusIds = chartDataCondition.cusIdSet;

			if (chartDataCondition) {
				SelectDom.initWithSpace($("#filterChartDialog_cusIdSel"));

				for (i = 0; i < cusIds.length; i++) {
					SelectDom.addSelect($("#filterChartDialog_cusIdSel"),
							cusIds[i]);
				}
			}
		},

		setMdlId : function(cusId) {
			var chartDataCondition = GlobalBean.chartDataCondition;
			var i, mdlOary;
			if (chartDataCondition) {

				mdlOary = cusId
						? chartDataCondition.cusMdlMap[cusId]
						: chartDataCondition.mdlIdSet;

				SelectDom.initWithSpace($("#filterChartDialog_mdlIdSel"));

				for (i = 0; i < mdlOary.length; i++) {
					SelectDom.addSelect($("#filterChartDialog_mdlIdSel"),
							BaseFnc.replaceSpace(mdlOary[i]), mdlOary[i]);
				}
			}
		},
		setWoId : function(mdlId) {
			var chartDataCondition = GlobalBean.chartDataCondition;
			var i, woOary;
			mdlId = BaseFnc.returnSpace(mdlId);

			if (chartDataCondition) {

				woOary = mdlId
						? chartDataCondition.mdlWoMap[mdlId]
						: chartDataCondition.woIdSet;

				SelectDom.initWithSpace($("#filterChartDialog_woIdSel"));

				for (i = 0; i < woOary.length; i++) {
					SelectDom.addSelect($("#filterChartDialog_woIdSel"),
							woOary[i]);
				}

			}

		},
		setLotId : function(woId) {
			var chartDataCondition = GlobalBean.chartDataCondition;
			var i, lotOary;

			lotOary = woId ? chartDataCondition.woLotMap[woId]: chartDataCondition.woIdSet;

			SelectDom.initWithSpace($("#filterChartDialog_lotIdSel"));

			for (i = 0; i < lotOary.length; i++) {
				SelectDom.addSelect($("#filterChartDialog_lotIdSel"),
						lotOary[i]);
			}
		},
		setOpeId : function() {
			var chartDataCondition = GlobalBean.chartDataCondition;
			var i, opeOary;

			opeOary = chartDataCondition.opeIdSet;

			SelectDom.initWithSpace($("#filterChartDialog_opeIdSel"));

			for (i = 0; i < opeOary.length; i++) {
				SelectDom.addSelect($("#filterChartDialog_opeIdSel"),
						opeOary[i]);
			}

		},
		setToolId : function(opeId) {
			var chartDataCondition = GlobalBean.chartDataCondition;
			var i, toolOary;

			toolOary = opeId
					? chartDataCondition.opeToolMap[opeId]
					: chartDataCondition.toolIdSet;

			SelectDom.initWithSpace($("#filterChartDialog_toolIdSel"));

			for (i = 0; i < toolOary.length; i++) {
				SelectDom.addSelect($("#filterChartDialog_toolIdSel"),
						toolOary[i]);
			}
		}
	}

	$("#filterChartDialog").on("change", "#filterChartDialog_cusIdSel",
			function() {
				FilterDialog.setMdlId($("#filterChartDialog_cusIdSel").val());
				// FilterDialog.setWoId($("#filterChartDialog_mdlIdSel").val());
		})
	$("#filterChartDialog").on("change", "#filterChartDialog_mdlIdSel",
			function() {
				FilterDialog.setWoId($("#filterChartDialog_mdlIdSel").val());
			})

	/*$("#filterChartDialog").on("change", "#filterChartDialog_woIdSel",
			function() {
				FilterDialog.setLotId($("#filterChartDialog_woIdSel").val());
			})*/

	$("#filterChartDialog").on("change", "#filterChartDialog_opeIdSel",
			function() {
				FilterDialog.setToolId($("#filterChartDialog_opeIdSel").val(),
						"00000");
			})
	$("#filterChartDialog").on("click", "#filterChartDialog_queryBtn",
			function() {
				var cusId, mdlId, woId, lotId, pToolId, pOpeId, fromTime, endTime, reportBeginDate, reportBeginTime, reportEndDate, reportEndTime, reportBeginTimestamp, reportEndTimestamp;

				cusId = $("#filterChartDialog_cusIdSel").val();
				mdlId = BaseFnc.returnSpace($("#filterChartDialog_mdlIdSel")
						.val());
				woId = $("#filterChartDialog_woIdSel").val();
				/*lotId = $("#filterChartDialog_lotIdSel").val();*/
				pToolId = $("#filterChartDialog_toolIdSel").val();
				pOpeId = $("#filterChartDialog_opeIdSel").val();

				// 当没有管制图显示时，不能进行筛选
				if (GlobalBean.displayChartCount <= 0) {
					showErrorDialog("", "当前没有可以被筛选的管制图");
					return false;
				}

				// 添加时间的防呆 ， 选日期同时必须选时间
				reportBeginDate = $("#filterChartDialog_reportBeginDatepicker input")
						.val();
				reportBeginTime = $("#filterChartDialog_reportBeginTimepicker input")
						.val();
				reportEndDate = $("#filterChartDialog_reportEndDatepicker input")
						.val()
				reportEndTime = $("#filterChartDialog_reportEndTimepicker input")
						.val();
				if ((!reportBeginDate && reportBeginTime)
						|| (reportBeginDate && !reportBeginTime)) {
					showErrorDialog("", "开始日期和时间必须同时选择");
					return false;
				}
				if ((!reportEndDate && reportEndTime)
						|| (reportEndDate && !reportEndTime)) {
					showErrorDialog("", "结束日期和时间必须同时选择");
					return false;
				}
				// // 时间前面增加checkbox，判定是否增加时间条件
				// if (!reportBeginDate || !reportBeginTime) {
				// showErrorDialog("", "请选择上报开始时间");
				// return false;
				// }

				// if (!reportEndDate || !reportEndTime) {
				// showErrorDialog("", "请选择上报结束时间")
				// return false;
				// }

				if ((reportBeginDate && reportBeginTime)
						&& (!reportEndDate || !reportEndDate)) {

					reportBeginTimestamp = reportBeginDate + " "
							+ reportBeginTime;

					reportEndTimestamp = null;

				} else if ((!reportBeginDate || !reportBeginTime)
						&& (reportEndDate && reportEndDate)) {

					reportEndTimestamp = reportEndDate + " " + reportEndTime;

					reportBeginTimestamp = null;

				} else if(reportBeginDate && reportBeginTime && reportEndDate && reportEndDate) {

					reportBeginTimestamp = reportBeginDate + " "
							+ reportBeginTime;

					reportEndTimestamp = reportEndDate + " " + reportEndTime;

				}

				filterChartFnc(cusId, mdlId, woId, lotId, pToolId, pOpeId, reportBeginTimestamp,
						reportEndTimestamp);
				$("#filterChartDialog").modal("hide");
				
				$("#cusIdSel").val(cusId);
				$("#mdlIdSel").val(BaseFnc.replaceSpace(mdlId));
				$("#woIdSel").val(woId);
				/*$("#lotIdSel").val(lotId);*/
				$("#eqptIdSel").val(pToolId);
				$("#opeIdSel").val(pOpeId);
		
				$("#reportBeginDatepicker input").val(reportBeginDate);
				$("#reportBeginTimepicker input").val(reportBeginTime);
				$("#reportEndDatepicker input").val(reportEndDate)
				$("#reportEndTimepicker input").val(reportEndTime);

			})

	// $("#filterChartDialog_fromTimestamp,#filterChartDialog_toTimestamp").datetimepicker({
	// format : "yyyy-mm-dd hh:mm:ss",
	// language:"zh-CN"
	// // forceParse:true,
	// // autoclose:true
	// })
	function showFilterChartDialog() {

		// 当没有管制图显示时，不能进行筛选
		if (GlobalBean.displayChartCount <= 0) {
			showErrorDialog("", "当前没有可以被筛选的管制图");
			return false;
		}
		
		var inTrx = {
			trx_id :"XPCCHTDT",
			action_flg:"D",
			col_typ : GlobalBean.selectedChart.col_typ,
			grp_no : GlobalBean.selectedChart.grp_no,
			chart_no : GlobalBean.selectedChart.chart_no,
			chart_typ : GlobalBean.selectedChart.chart_typ
		};

//		url = "distinctChartCondition";
		outTrx = comTrxSubSendPostJson(inTrx);
		/*outTrx = comSendAjax(_GET, url, inTrx).outPo;*/
		console.info(outTrx);
		if (outTrx.rtn_code == _NORMAL) {
			GlobalBean.chartDataCondition = outTrx.chartDataCondition;
		}

		FilterDialog.setCusId();
		FilterDialog.setMdlId($("#filterChartDialog_cusIdSel").val());
		FilterDialog.setWoId($("#filterChartDialog_mdlIdSel").val());
		FilterDialog.setOpeId();
		FilterDialog.setToolId($("#filterChartDialog_opeIdSel").val(), "00000");
		$("#filterChartDialog").modal("show");
	}
	$("#f12_btn").click(function() {
				showFilterChartDialog();
				
			})
})
